package cn.gs.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 第二个过滤器(加注解)，url中参数不符合要求，将拒绝请求
 */
@WebFilter(filterName = "parameterFilter", urlPatterns = {"/*"})
@Component
public class ParameterFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 在这里可以初始化配置
        System.out.println("第二个过滤器，在这里可以初始化配置。。。。。。");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        // 获取请求参数
        String parameterValue = httpRequest.getParameter("paramName");

        if ("unwantedValue".equals(parameterValue)) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            // 设置状态码为403，表示禁止访问
            httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
            // 可以返回一些错误信息
            httpResponse.getWriter().write("Parameter value not allowed");
        } else {
            // 继续请求链
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        // 在这里可以进行资源清理
    }
}